import axios, {type Method} from "axios";
import type {IResponse} from '@/types/data'
import useTokenStore from '@/stores/token';
const service = axios.create({
    baseURL:'http://interview-api-t.itheima.net/',
    timeout:10000
})

service.interceptors.request.use(
  (config) => {
      const {getToken} = useTokenStore()
      if(getToken()){
        config.headers.Authorization = `Bearer ${getToken()}`
      }
      return config
    }
)

service.interceptors.response.use((response) => response.data)

const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
    // 泛型的第二个参数，可以自定义响应数据类型
    return service.request<T, IResponse<T>>({
      url,
      method,
      // 区分get和其他请求post
      // get 提交数据，选项：params
      // 其他请求post 提交数据，选项：data
      [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
    })
  }

export default request